<template>
    <div class="jianzhan-content">
        <Crumb name="Import&Export"></Crumb>
        <div class="content">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Ship"
                        prefix-icon="el-icon-search"
                ></el-input>
                <el-button type="text" class="btn" size="small" @click="showEdit = !showEdit">{{btnText}}</el-button>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="exportList"
                        border
                        stripe
                        style="width: 100%">
                    <el-table-column type="expand">
                        <template slot-scope="scope">

                            <div>
                                <span>装船明细 Container Info: </span>
                                <a class="link" :href="scope.row.packingDetails">{{ scope.row.packingDetails |
                                    getName}}</a>
                            </div>
                            <div>
                                <span>sppb: </span>
                                <a class="link" :href="scope.row.sppbJianZhan">{{ scope.row.sppbJianZhan | getName
                                    }}</a>
                                <a class="link" :href="scope.row.sppbShanQi">{{ scope.row.sppbShanQi | getName }}</a>
                            </div>
                            <div>
                                <span>联系单／装船数据: Ship data </span>
                                <a class="link" :href="scope.row.shipmentData">{{ scope.row.shipmentData | getName
                                    }}</a>
                            </div>
                            <el-button type="text" size="small"
                                       v-if="urlAvailible('/jianzhan/iel') || urlAvailible('/iel/customer')"
                                       @click="downloadZip(scope.row.shipInformation)" icon="el-icon-download">Download
                                ZIP
                            </el-button>
                            <el-collapse>
                                <el-collapse-item title="Shacman Packing List">
                                    <div v-for="(value,key) in scope.row.sendGoodsOrderInformation" :key="value">
                                        <span>{{key}}</span>
                                        <div v-for="(item,idx) in value? value.split(',') : []" :key="idx">
                                            <span style="display: inline-block;margin-left: 30px;">
                                                 <a :href="item" class="link">{{item | getName}}</a>
                                            </span>
                                        </div>
                                    </div>
                                </el-collapse-item>
                                <el-collapse-item title="IEL-Customer Packing List">
                                    <div class="link" v-if="urlAvailible('/iel/customer') &&  scope.row.ielCustomer">
                                        <div>
                                            <h5> IEL-IEC</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.ielCustomer) ? (JSON.parse(scope.row.ielCustomer).IELIEC) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.ielCustomer).iec2c">
                                                    单号:{{JSON.parse(scope.row.ielCustomer).iec2c.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.ielCustomer).iec2c.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>

                                        </div>
                                        <div>
                                            <h5> IEL-ITSS</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.ielCustomer) ? (JSON.parse(scope.row.ielCustomer).IELITSS) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.ielCustomer).itss2c">
                                                    单号:{{JSON.parse(scope.row.ielCustomer).itss2c.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.ielCustomer).itss2c.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>

                                        </div>
                                        <div>
                                            <h5> IEL-KST</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.ielCustomer) ? (JSON.parse(scope.row.ielCustomer).IELKST) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.ielCustomer).kst2c">
                                                    单号:{{JSON.parse(scope.row.ielCustomer).kst2c.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.ielCustomer).kst2c.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>

                                        </div>
                                        <div>
                                            <h5> IEL-TID</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.ielCustomer) ? (JSON.parse(scope.row.ielCustomer).IELTID) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.ielCustomer).tid2c">
                                                    单号:{{JSON.parse(scope.row.ielCustomer).tid2c.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.ielCustomer).tid2c.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>

                                        </div>
                                    </div>
                                    <div v-else>Data is not available</div>
                                </el-collapse-item>
                                <el-collapse-item title="SHI-IEL Packing List">
                                    <div class="link" v-if="urlAvailible('/jianzhan/iel') && scope.row.jianzhanIel">
                                        <div>
                                            <h5>SHI-IEL-IEC</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.jianzhanIel) ? (JSON.parse(scope.row.jianzhanIel).SHIIELIEC) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.jianzhanIel).iec">
                                                    单号:{{JSON.parse(scope.row.jianzhanIel).iec.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.jianzhanIel).iec.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>
                                        </div>
                                        <div>
                                            <h5>SHI-IEL-ITSS</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.jianzhanIel) ? (JSON.parse(scope.row.jianzhanIel).SHIIELITSS) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.jianzhanIel).itss">
                                                    单号:{{JSON.parse(scope.row.jianzhanIel).itss.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.jianzhanIel).itss.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>
                                        </div>
                                        <div>
                                            <h5>SHI-IEL-KST</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.jianzhanIel) ? (JSON.parse(scope.row.jianzhanIel).SHIIELKST) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.jianzhanIel).kst">
                                                    单号:{{JSON.parse(scope.row.jianzhanIel).kst.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.jianzhanIel).kst.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>
                                        </div>
                                        <div>
                                            <h5>SHI-IEL-TID</h5>
                                            <div v-for="(item,idx) in JSON.parse(scope.row.jianzhanIel) ? (JSON.parse(scope.row.jianzhanIel).SHIIELTID) : []"
                                                 :key="idx">
                                                <div v-if="JSON.parse(scope.row.jianzhanIel).tid">
                                                    单号:{{JSON.parse(scope.row.jianzhanIel).tid.orderNo}} -
                                                    <span v-if="idx  === 0">箱数:{{JSON.parse(scope.row.jianzhanIel).tid.price}}</span>
                                                </div>
                                                <a :href="item">
                                                    {{item | getName}}
                                                </a>
                                            </div>
                                        </div>

                                    </div>
                                    <div v-else>Data is not available</div>
                                </el-collapse-item>
                            </el-collapse>


                        </template>
                    </el-table-column>
                    <el-table-column
                            label="Index"
                            type="index"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="shipInformation"
                            width="150px"
                            :filters="shipFilters"
                            :filter-method="filterHandler"
                            label="船名船次／shipment"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="originatingPort"
                            label="始发港／departure"
                            :filters="[{text:'ZJG',value:'ZJG'},{text:'SH',value:'SH'},{text:'NB',value:'NB'}]"
                            :filter-method="filterHandler"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="concentratedPortDateStr"
                            label="集港日期"
                    >
                    </el-table-column>
                    <el-table-column
                            sortable
                            prop="leaveDateStr"
                            label="开船日期／ETD"
                    >
                    </el-table-column>
                    <el-table-column
                            width="80px"
                            prop="destinationPort"
                            label="目的港／Arrival"
                            :filters="[
                                {text:'POSO',value:'POSO'},
                                {text:'WEDA',value:'WEDA'},
                                {text:'JAK',value:'JAK'},
                                {text:'MOROWALI',value:'MOROWALI'}
                            ]"
                            :filter-method="filterHandler"
                    >
                    </el-table-column>
                    <el-table-column
                            sortable
                            prop="arrivalDateStr"
                            label="到港日期／ETA"
                    >
                    </el-table-column>

                    <el-table-column
                            sortable
                            prop="releaseDateStr"
                            label="放行日期／SPPB"
                    >
                    </el-table-column>
                    <!--<el-table-column sortable label="出口／Exporter" prop="exporter"></el-table-column>-->
                    <el-table-column
                            label="状态"
                    >
                        <template slot-scope="scope">
                            <span>{{statusList[scope.row.status] ? (statusList[scope.row.status]['label']) : ''}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            v-if="showEdit"
                            width="150px"
                    >
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="openEdit(scope.row)"
                            >Edit
                            </el-button>
                            <div style="margin-top: 5px">
                                <el-button type="text" size="small" @click="showStock(scope.row)">Show Stock</el-button>
                            </div>

                        </template>
                    </el-table-column>

                </el-table>
                <div class="page">
                    <el-pagination background
                                   @current-change="changePage"
                                   :page-size="pageSize"
                                   layout="prev, pager, next"
                                   :total="total"></el-pagination>
                </div>

            </div>

            <div class="modal-wrapper">
                <el-dialog
                        title="出口"
                        :visible.sync="dialogVisible"
                        width="80%"
                >
                    <el-form ref="form" :model="ruleForm" :rules="rule" label-width="150px" style="text-align: left">
                        <div style="display: flex">
                            <div style="flex: 1">
                                <el-form-item label="船名船次／Shipment" prop="shipInformation">
                                    <el-input v-model="ruleForm.shipInformation" placeholder="船名船次" size="small"
                                              class="my-input"></el-input>
                                </el-form-item>
                                <el-form-item label="始发港／Departure">
                                    <el-input v-model="ruleForm.originatingPort" placeholder="始发港" size="small"
                                              class="my-input"></el-input>
                                </el-form-item>
                                <el-form-item label="集港日期">
                                    <el-date-picker v-model="ruleForm.concentratedPortDateStr" type="date"
                                                    placeholder="集港日期" class="my-input" size="small"
                                                    value-format="yyyy-MM-dd"></el-date-picker>
                                </el-form-item>
                                <el-form-item label="开船日期">
                                    <el-date-picker v-model="ruleForm.leaveDateStr" type="date" placeholder="开船日期"
                                                    size="small" class="my-input"
                                                    value-format="yyyy-MM-dd"></el-date-picker>
                                </el-form-item>
                                <el-form-item label="目的港／Arrival" prop="destinationPort">
                                    <el-input v-model="ruleForm.destinationPort" placeholder="目的港" class="my-input"
                                              size="small"></el-input>
                                </el-form-item>
                                <el-form-item label="到港日期／ETA">
                                    <el-date-picker v-model="ruleForm.arrivalDateStr" placeholder="到港日期"
                                                    class="my-input" value-format="yyyy-MM-dd"
                                                    size="small"></el-date-picker>
                                </el-form-item>
                                <el-form-item label="放行日期／SPPB">
                                    <el-date-picker v-model="ruleForm.releaseDateStr" placeholder="放行日期"
                                                    class="my-input" value-format="yyyy-MM-dd"
                                                    size="small"></el-date-picker>
                                </el-form-item>
                            </div>
                            <div style="flex: 1;">
                                <el-form-item label="Total Box">
                                    <el-input v-model="ruleForm.totalBox" placeholder="总箱数" class="my-input"
                                              size="small"></el-input>
                                </el-form-item>
                                <el-form-item label="Consignment" prop="freight">
                                    <el-select v-model="ruleForm.freightList" style="width: 100%" class="my-input"
                                               multiple placeholder="发运合同" size="small">
                                        <el-option
                                                v-for="item in deliveryList"
                                                :key="item.id"
                                                :label="item.sendGoodsContract"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="Status">
                                    <el-select v-model="ruleForm.status" class="my-input" placeholder="状态">
                                        <el-option
                                                v-for="item in statusList"
                                                :key="item.key"
                                                :label="item.label"
                                                :value="item.key">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </div>
                        </div>


                        <el-form-item label="整单shipment费用">
                            <el-input v-model="ruleForm.shipmentPrice" size="small"
                                      placeholder="整单shipment费用"></el-input>
                        </el-form-item>

                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                    </span>
                </el-dialog>
                <stock-dialog
                        :stock-info-list="stockInfoList"
                        :first="first"
                        :last="last"
                        ref="stock">
                </stock-dialog>
            </div>
        </div>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import stockDialog from '../../components/shanxi/stockInfoDialog'
    import mixins from '../../util/mixins'
    import authMixins from '../../util/authMixins'
    import {getAllExportInfo} from "../../api/service";
    import {addExport, modExport, getDeliveryList} from "../../api/contract";
    import {upLoadFiles} from "../../api";
    import {ERROR_OK} from "../../util/config";
    import {arrayUnique, getFileName} from "../../util";
    import {baseURL} from "../../util";
    import {getStockInfoByShip} from "../../api/shanxi";

    export default {
        name: "export",
        mixins: [mixins, authMixins],
        data() {
            return {
                showEdit: false,
                first:{},
                last:{},
                list: [],
                deliveryList: [],
                stockInfoList: [],
                shipFilters:[],
                departureFilters:[],

                ruleForm: {
                    shipInformation: '',
                    destinationPort: '',
                    arrivalDateStr: '',
                    leaveDateStr: '',
                    totalBox: '',
                    freightList: [],
                    concentratedPortDateStr: '',
                    releaseDateStr: '',
                    originatingPort: '',
                    shipmentPrice: '',
                    invoice: [{
                        billOfLading: '',
                        invoice: '',
                        invoiceAmount: '',
                        pibAju: '',
                        amount: ''
                    }],
                    status: ''
                },
                fileList: [],
                rule: {
                    shipInformation: [
                        {required: true, message: '船名船次不能为空', trigger: 'blur'},
                    ],
                    destinationPort: [
                        {required: true, message: '目的港口不能为空', trigger: 'blur'}
                    ],
                    freightList: [
                        {required: true, message: '发运合同不能为空', trigger: 'blur'}
                    ]
                },
                key: '',
                dialogVisible: false
            }
        },
        filters: {
            getName(name) {
                return getFileName(name)
            }
        },
        created() {
            this.getExportList();
            this.getDeliveryList();
            this.statusList = [{key: 0, label: '出厂／Leave Factory'}, {key: 1, label: '开船／DEPARTURED'}, {
                key: 2,
                label: '到岗／ARRIVED'
            }, {key: 3, label: '放行／SPPB'}, {key: 4, label: '入库／Stock In'}]
        },
        computed: {
            btnText() {
                return this.showEdit ? 'Complete' : 'Edit'
            },
            exportList() {
                return this.list.filter(item => item.shipInformation.includes(this.key))
                    .slice((this.pageNum - 1) * this.pageSize, this.pageNum * this.pageSize)
            }
        },
        methods: {
            async showStock(row) {
                const {status, data} = await getStockInfoByShip(row.shipInformation);
                if (status === ERROR_OK) {
                    this.stockInfoList = data.record;
                    this.first = data.first || {};
                    this.last = data.last || {};
                    this.$refs.stock.open();
                }
            },
            downloadZip(shipInformation) {
                window.open(baseURL + '/zip_download/manage/all_download_file.file?shipInformation=' + shipInformation)
            },
            filterHandler(value, row, column) {
                const property = column['property'];
                return row[property] === value;
            },
            clear() {
                this.ruleForm = {
                    shipInformation: '',
                    destinationPort: '',
                    arrivalDateStr: '',
                    leaveDateStr: '',
                    totalBox: '',
                    concentratedPortDateStr: '',
                    releaseDateStr: '',
                    originatingPort: '',
                    shipmentPrice: '',
                    freightList: [],
                    invoice: [{
                        billOfLading: '',
                        invoice: '',
                        invoiceAmount: '',
                        pibAju: '',
                        amount: ''
                    }],
                    exportStatus: ''
                };
            },
            addInvoice() {
                this.ruleForm.invoice.push({
                    billOfLading: '',
                    invoice: '',
                    invoiceAmount: '',
                    pibAju: '',
                    amount: ''
                })
            },
            async getDeliveryList() {
                const {status, data} = await getDeliveryList();
                if (status === ERROR_OK) {
                    this.deliveryList = data
                }
            },
            submitForm() {
                this.$refs.form.validate(async valid => {
                    if (valid) {
                        const {shipInformation, destinationPort, arrivalDateStr, leaveDateStr, totalBox, exportStatus, id, concentratedPortDateStr, releaseDateStr, originatingPort, shipmentPrice} = this.ruleForm;
                        let {freightList, invoice} = this.ruleForm;
                        freightList = freightList.join(',');
                        invoice = JSON.stringify(invoice);
                        if (this.ruleForm.id) {
                            const {status} = await modExport({
                                id,
                                shipInformation,
                                destinationPort,
                                arrivalDateStr,
                                leaveDateStr,
                                totalBox,
                                exportStatus,
                                freightList,
                                invoice,
                                concentratedPortDateStr,
                                releaseDateStr,
                                originatingPort,
                                shipmentPrice
                            });
                            if (status === ERROR_OK) {
                                this.$notify.success('修改出口单成功');
                                this.clear();
                                this.getExportList();
                                this.dialogVisible = false
                            }
                        } else {
                            const {status} = await addExport({
                                shipInformation,
                                destinationPort,
                                arrivalDateStr,
                                leaveDateStr,
                                totalBox,
                                exportStatus,
                                freightList,
                                invoice,
                                concentratedPortDateStr,
                                releaseDateStr,
                                originatingPort,
                                shipmentPrice
                            });
                            if (status === ERROR_OK) {
                                this.$notify.success('添加出口单成功');
                                this.clear();
                                this.getExportList();
                                this.dialogVisible = false
                            }
                        }

                    }
                })
            },
            async getExportList() {
                const {status, data, msg} = await getAllExportInfo();
                if (status === ERROR_OK) {
                    this.list = data;
                    this.shipFilters = arrayUnique(
                        data.filter(item => !item.shipInformation.includes('待定')).
                        map(item => {
                            return item.shipInformation
                        })).map(item => {
                            return {
                                text:item,
                                value:item
                            }
                    });

                } else {
                    this.$notify.error(msg)
                }
            },
            async fileChange(e) {
                const formData = new FormData();
                Array.prototype.forEach.call(e.target.files, item => {
                    formData.append('upload_file', item)
                });
                const {success, file_path} = await upLoadFiles(formData);
                if (success) {
                    this.fileList = file_path
                }
            },
            openAdd() {
                this.clear();
                this.dialogVisible = true
            },
            openEdit(row) {
                const freightList = row.freightList ? row.freightList.toString().split(',').map(item => parseInt(item, 10)) : []
                this.ruleForm = {
                    ...row,
                    freightList
                };
                this.dialogVisible = true
            }
        },
        watch: {
            exportList(list) {
                this.total = list.length
            }
        },
        components: {
            Crumb, Search, stockDialog
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";
    @import "../../css/variable";

    .content {
        @include content
    }

    .btn {
        float: right;
        margin-right: 20px;
        transition: all 1s ease;
        opacity: 0.5;
        &:hover {
            opacity: 1;
        }
    }

    .label-btn {
        display: block;
        width: 150px;
        height: 30px;
        line-height: 30px;
        background-color: $bg-theme;
        color: white;
        padding: 0 5px;
        cursor: pointer;
        border-radius: 3px;
        text-align: center;
    }

    .file-list {
        font-size: 16px;
        .file-item {
            height: 25px;
            line-height: 25px;
            border-bottom: 1px solid #ddd;

        }
    }

    a {
        color: #409eff;
        text-decoration: underline;
    }

</style>